package com.qidian.tcba.utils;

/**
 * @author:fyl
 * @date 2021/8/5 10:37
 * @Modified By:
 * @Modified Date:
 * @Description:
 */
// 在Java中使用MessageDigest实现MD5，SHA-1等加密
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/*
 * TestEncrypt.java Description: A test progrm to encrypt a string using MD5 or SHA-1,etc.
 */

public class MessageEncrypt {

    /**
     * @param strSrc 要加密的字符串
     * @param encName 加密算法
     * @return
     */
    public static String encrypt(String strSrc, String encName) {
        // parameter strSrc is a string will be encrypted,
        // parameter encName is the algorithm name will be used.
        // encName dafault to "MD5"
        // 得到MessageDigest对象
        MessageDigest md = null;
        MessageEncrypt mept = new MessageEncrypt();
        // 加密后的字符串
        String strDes = null;
        // 要加密的字符串字节型数组
        byte[] bt = strSrc.getBytes();
        try {
            if (encName == null || encName.equals("")) {
                encName = "MD5";
            }
            md = MessageDigest.getInstance(encName);
            md.update(bt);
            // 通过执行诸如填充之类的最终操作完成哈希计算
            strDes = mept.bytes2Hex(md.digest()); // to HexString
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Invalid algorithm.\n" + e.getMessage());
            return null;
        }
        return strDes;
    }

    // 将字节数组转换成16进制的字符串
    private String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;

        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

}